const server = require('../../../utils/server');
const App = getApp();

Page({
  data: {
    flavor: [],
    flavorId: '',
    flavorName: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getFlavor();
  },
  getFlavor: function () {  //获取口味
    let that = this;
    server.postJSON('getFlavor', function (res) {
      if (res.data.status === 200) {
        that.setData({
          flavor: res.data.data
        })
      }
    });
  },
  openMenu: function(e){
    console.log(e)
    let that = this;
    let data = e.currentTarget.dataset;
    wx.showActionSheet({
      itemList: ['修改', '删除'],
      success: function (res) {
        if (res.tapIndex === 0) {
          that.setData({
            flavorName: data.name,
            flavorId: data.id
          })
        } else if (res.tapIndex === 1) {
          server.postJSON('delFlavor', { _id: data.id}, function (res) {
            if (res.data.status === 200) {
              that.setData({
                flavor: that.data.flavor.splice(data.idx,1)
              })
              that.getFlavor();
            }
          });
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  saveCase: function (e) {
    let that = this;
    if (!e.detail.value.flavorName) {
      return wx.showToast({
        icon: 'none',
        title: '口味不能为空',
      })
    }
    server.postJSON('saveFlavor', e.detail.value, function (res) {
      if (res.data.status === 200) {
        wx.showModal({
          title: '温馨提示',
          content: res.data.msg + ' 是否继续添加？',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                flavorName: '',
                flavorId: ''
              })
              that.getFlavor();
            } else if (res.cancel) {
              console.log('用户点击取消')
              setTimeout(() => {
                wx.navigateBack()
              }, 200)
            }
          }
        })
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})